<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class HYD_Admin {

    /**
     * ci instance
     *
     * @access private
     * @var string
     */
    protected $_ci = NULL;

    /**
     * admin data
     *
     * @access private
     * @var array
     */
    private $_data = array();

    /**
     * obj_access
     *
     * @access private
     * @var array
     */
    private $_obj_access = NULL;

    /**
     * HYD Customer Constructor
     * 
     * @access public
     */
    public function __construct() {
        // Set the super object to a local variable for use later
        $this->_ci = & get_instance();

        // Grab the customer data array from the session table, if it exists
        if ($this->_ci->session->userdata('user_data') !== FALSE) {
            $this->_data = $this->_ci->session->userdata('user_data');
        }
        $this->_ci->load->model('userlog/userlog_model');
        //log_message('Debug', "HYD Admin Class Initialized");
    }

    /**
     * Get admin id
     *
     * @access public
     * @return mixed $value
     */
    public function get_id() {
        if (isset($this->_data['id']) && is_numeric($this->_data['id'])) {
            return $this->_data['id'];
        }

        return FALSE;
    }

    /**
     * Get username
     *
     * @access public
     * @return mixed $value
     */
    public function get_username() {
        $username = NULL;

        if (isset($this->_data['username'])) {
            $username = $this->_data['username'];
        }

        return $username;
    }

    /**
     * Check whether admin is logged in
     *
     * @access public
     * @return mixed $value
     */
    public function is_logged_on() {
        $logged_on = NULL;

        if (is_null($logged_on)) {
            $logged_on = isset($this->_data['id']) && !empty($this->_data['id']);
        }

        return $logged_on;
    }

    /**
     * 加载模块access类
     * @return boolean
     */
    public function load_module_access($module = '') {
        if (empty($module))
            return FALSE;
        $module_class = 'HYD_Access_' . ucfirst($module);
        if (is_subclass_of($this->_obj_access, $module_class))
            return TRUE;
        $access_file = APPPATH . 'modules/' . $module . '/access/' . $module . '.php';
        if (file_exists($access_file)) {
            if (!class_exists($module_class)) {
                include($access_file);
            }
            $ac = new $module_class();
            $this->_obj_access = &$ac;
            return TRUE;
        } else {
            log_message('error', "File $access_file is not exists.");
        }
        return FALSE;
    }

    /**
     * 检查模块默认权限
     * @param type $module
     * @param type $action
     * @return boolean
     */
    public function check_default_privilege($module = '', $action = '') {
        if ($this->load_module_access($module)) {
            $default_privilege = $this->_obj_access->get_default_privileges();
            if (in_array($action, array_keys($default_privilege))) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
        return FALSE;
    }

    /**
     * 检查模块操作权限
     *
     * @param string  $module 模块名称
     * @param string $action 方法 
     * @access public
     * @return bool 
     */
    public function check_privilege($module, $action = NULL) {
        $module_info = $this->_ci->access_model->get_group_resources($this->get_group_id(), $module);
        if (count($module_info) > 0) {
            $action_arr = explode('_', $action);
            //查看权限
            if (is_null($action) || empty($action)) {
                return TRUE;
            } elseif ($this->check_default_privilege($module, $action_arr[0])) {
                return TRUE;
            } else {
                if ($this->load_module_access($module)) {
                    $defined_valid_privileges = $this->_obj_access->get_defined_valid_privileges($this->is_root());
                    //module access中未定义或不允许非root机构使用此action                  
                    if (!in_array($action_arr[0], array_keys($defined_valid_privileges))) {
                        return FALSE;
                    } else {
                        $acl_arr = explode(',', $module_info['fd_acl']);
                        if (in_array($action_arr[0], $acl_arr)) {
                            return TRUE;
                        } else {
                            return FALSE;
                        }
                    }
                }
            }
        }
        return FALSE;
    }

    /**
     * 获取指定模块可操作action列表(视图使用)
     *
     * @param string  $module 模块名称
     * @access public
     * @return array $res_array 
     */
    public function get_privilege_lists($module) {
        $res_array = array();
        $module_info = $this->_ci->access_model->get_group_resources($this->get_group_id(), $module);
        if (count($module_info) > 0) {
            $acl_arr = explode(',', $module_info['fd_acl']);
            if ($this->load_module_access($module)) {
                $res_array = $this->_obj_access->get_default_privileges();
                $defined_valid_privileges = $this->_obj_access->get_defined_valid_privileges($this->is_root());
                //module access中未定义或不允许非root机构使用此action
                //与授权信息比对,返回共有的action
                foreach ($defined_valid_privileges as $key => $value) {
                    if (in_array($key, $acl_arr)) {
                        $res_array[$key] = $value;
                    }
                }
            }
        }
        return $res_array;
    }

    /**
     * Check whether admin is locked
     *
     * @access public
     * @return mixed $value
     */
    public function is_locked() {
        $is_locked = NULL;

        if (isset($this->_data['is_locked'])) {
            $is_locked = $this->_data['is_locked'];
        }

        return $is_locked;
    }

    /**
     * Check whether organization is root
     *
     * @access public
     * @return bool $value
     */
    public function is_root() {
        $is_root = NULL;
        if (is_null($is_root)) {
            if ($this->get_organization_id() == 0)
                $is_root = TRUE;
            else
                $is_root = FALSE;
        }

        return $is_root;
    }

    /**
     * Get desktop settings
     *
     * @access public
     * @return mixed $value
     */
    public function get_settings() {
        $settings = null;


        if (isset($this->_data['settings'])) {
            $settings = $this->_data['settings'];
        }


        return $settings;
    }

    /**
     * Get email
     *
     * @access public
     * @return mixed $value
     */
    public function get_email() {
        $email = null;


        if (isset($this->_data['email'])) {
            $email = $this->_data['email'];
        }


        return $email;
    }

    /**
     * Get name
     *
     * @access public
     * @return mixed $value
     */
    public function get_name() {
        $name = null;


        if (isset($this->_data['name'])) {
            $name = $this->_data['name'];
        }


        return $name;
    }

    /**
     * Get department_id
     *
     * @access public
     * @return mixed $value
     */
    public function get_department_id() {
        $department_id = null;


        if (isset($this->_data['department_id'])) {
            $department_id = $this->_data['department_id'];
        }


        return $department_id;
    }

    /**
     * Get group_id
     *
     * @access public
     * @return mixed $value
     */
    public function get_group_id() {
        $group_id = null;


        if (isset($this->_data['group_id'])) {
            $group_id = $this->_data['group_id'];
        }


        return $group_id;
    }

    /**
     * Get organization_id
     *
     * @access public
     * @return mixed $value
     */
    public function get_organization_id() {
        $organization_id = null;


        if (isset($this->_data['organization_id'])) {
            $organization_id = $this->_data['organization_id'];
        }


        return $organization_id;
    }

    /**
     * do_userlog
     * 记录日志，后台使用
     * @param string $module 模块名称
     * @param string $action 方法
     * @param string $object 操作对象
     * @param string $description 操作内容
     * @param bool $neednotice   是否高亮显示
     * @param bool $result   方法是否执行成功
     * @return boolean TRUE 成功 FALSE 失败
     */
    public function do_userlog($module = '', $action = '', $object = '', $description = '', $result = FALSE, $neednotice = FALSE) {
        if (substr($object, 0, 8) == 'adminlog') return;
        if ($neednotice) {
            $neednotice = 'YES';
        } else {
            $neednotice = 'NO';
        }
        if ($result) {
            $result = 1;
        } else {
            $result = 0;
        }
        $this->_ci->load->helper('core_helper');
        $data = array('username' => $this->get_username(),
            'userip' => get_ip_address(),
            'neednotice' => $neednotice,
            'module' => $module,
            'action' => $action,
            'object' => $object,
            'description' => $description,
            'result' => $result,
            'createtime' => get_date_now()
        );
        if (empty($data['username']))
            $data['username'] = '';
        if ($this->_ci->userlog_model->save($data) == MODEL_RETURN_SUCCESS) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Perform login
     *
     * @access public
     * @param string $username
     */
    public function login($username) {
        $data = $this->_ci->user_model->get_data_username($username);

        //if admin data is not null
        if (count($data) > 0) {
            //更新登录人的状态和时间
            $this->_ci->load->library('user_agent');
            if ($this->_ci->agent->is_browser()) {
                $agent = $this->_ci->agent->browser() . ' ' . $this->_ci->agent->version();
            } elseif ($this->agent->is_robot()) {
                $agent = $this->_ci->agent->robot();
            } elseif ($this->_ci->agent->is_mobile()) {
                $agent = $this->_ci->agent->mobile();
            } else {
                $agent = '未能识别的浏览器';
            }
            $browser = $agent;
            $this->_ci->load->helper('core_helper');
            $lastloginip = get_ip_address();
            $this->_ci->user_model->save($data['id'], array('islogin' => 'YES',
                'lastlogintime' => date('Y-m-d H:i:s'),
                'lastloginip' => $lastloginip,
                'browser' => $browser));
            
            $this->_data = array();
            $this->_data['id'] = $data['id'];
            $this->_data['name'] = $data['name'];
            $this->_data['sex'] = $data['sex'];
            $this->_data['positionid'] = $data['positionid'];
            $this->_data['teamid'] = $data['teamid'];
            $this->_data['departmentid'] = $data['departmentid'];
            $this->_data['username'] = $data['username'];
            $this->_data['tel'] = $data['tel'];
            $this->_data['worknum'] = $data['worknum'];
            $this->_data['entrytime'] = $data['entrytime'];
            
            $this->_ci->load->model('team/team_model');
            $team_arr = $this->_ci->team_model->get_data($data['teamid']);
            $this->_data['team_name'] = $team_arr['name'];
            $this->_ci->load->model('department/department_model');
            $department_arr = $this->_ci->department_model->get_data($data['departmentid']);
            $this->_data['department_name'] = $department_arr['name'];
            $this->_ci->load->model('position/position_model');
            $position_arr = $this->_ci->position_model->get_data($data['positionid']);
            $this->_data['position_name'] = $position_arr['name'];
            
            $this->_ci->load->library('province_city');
            $this->_data['province_name'] = $this->_ci->province_city->get_province_name($data['provinceid']);
            $this->_data['city_name'] = $this->_ci->province_city->get_city_name($data['cityid']); 
            //set data to session
            $this->_ci->session->set_userdata('user_data', $this->_data);
        }
        //if user data is not found and session is not empty then reset session
        else if ($this->_ci->session->userdata('user_data') !== FALSE) {
            $this->reset();
        }
    }

    /**
     * Reset admin & session data.
     * 
     * @access public
     */
    public function reset() {
        $this->_ci->user_model->set_is_login($this->get_id(), FALSE);
        //clean customer data
        $this->_data = array();
        //clean session data
        $this->_ci->session->unset_userdata('user_data');
    }

}
// END HYD Class

